package com.wxtf.platform.plugins.user;

import java.util.*;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.*;
import org.hibernate.impl.SessionImpl;

import com.wxtf.platform.interfaces.CommonsCallProvider;
import com.wxtf.platform.supers.LogicBase;
import com.wxtf.platform.tools.AccessDataBaseUtil;
import com.wxtf.platform.tools.ConstantInfoHelper;
import com.wxtf.platform.tools.MD5;
import com.wxtf.platform.tools.ZipUtil;

/**
 * <li>Title: UserLoginAction.java</li>
 * <li>Project: baseplatform</li>
 * <li>Package: com.wxtf.platform.plugins.user</li>
 * <li>Description: 用户登录</li>
 * <li>Copyright: Copyright (c) 2012</li>
 * <li>Company: wxthtf Technologies </li>
 * <li>Created on Aug 29, 2012 4:49:48 PM</li>
 *
 * @author chun_chang
 * @version 1.0.0.0
 *
 */
public class UserLoginAction extends LogicBase implements CommonsCallProvider{

	private static Log log = LogFactory.getLog(UserLoginAction.class);
	//判断登陆成功的返回值
	private String message = "";

	@Override
	public Object run() {
		Object msg = "";
		JSONObject request_jso = new JSONObject();
		try {
			if("userLogic".equals(this.getMethodName())) {
				msg = this.select(this.getExtendData());
			} else if("listOrg".equals(this.getMethodName())) {
				msg = this.listOrg(this.getExtendData());
			} else if("downloadLog".equals(this.getMethodName())) {
				msg = this.downloadLog(this.getLogicData());
				return msg;
			} else if("logout".equals(this.getMethodName())) {
				msg = this.logout(this.getLogicData());
			} else if("updateOrg".equals(this.getMethodName())) {
				msg = this.updateOrg(this.getLogicData());
			}
			if(msg == null || "[null]".equals(msg)) {
				msg = "\"\"";
			}
			request_jso.put("result", "true");
			request_jso.put("resultmessage", message);
			request_jso.put("resultrecord", msg);
			JSONArray us_json = new JSONArray();
			us_json.add(request_jso);
		} catch(Exception e) {
			msg = "操作失败，请联系管理员";
			msg = ConstantInfoHelper.generateJSONString(ConstantInfoHelper.JSON_HEAD, ConstantInfoHelper
					.getFailResultDetail(msg.toString()), false);
			log.error(e, e);
		} finally {
			this.clear();
		}
		return request_jso.toString();
	}

	public UserLoginAction(String jsonArray){
	}

	@Override
	public Object onInit(Object jsonArray) {
		return null;
	}

	@Override
	public Object onCreate(Object jsonArray) {
		return null;
	}

	@Override
	public Object onDestory(Object jsonArray) {
		return null;
	}

	@Override
	public Object select(Object jsonArray) throws Exception {
		UserBean userBean = new UserBean();
		JSONArray array = JSONArray.fromObject(jsonArray);
		JSONObject jsonObject = JSONObject.fromObject(array.getString(0));
		String userName = jsonObject.getString("userName");
		String passWord = jsonObject.getString("passWord");
		String nowOrg = jsonObject.getString("nowOrgan");
		String verCode = jsonObject.getString("verCode");
		String msg = "";
		String userLay = "";
		String session_code = (String) ((HttpServletRequest) this.getRequest()).getSession().getAttribute("sess_code");//获取生成的验证码
		String sql = " from t_user r, t_user_info s where r.USER_ID = s.USER_ID";
		if(StringUtils.isNotBlank(userName)) {
			sql += " and r.action='" + userName + "' and s.user_passwd='" + MD5.md5(passWord) + "' and s.user_status='1' ";
		}
		// 获取用户信息
		String querySql = "select s.user_id, r.caption, s.real_name, s.user_education" + sql;
		// 获取系统环境变量与定义的用户变量
		String[] sys_global = { "sc_key", "sc_value" };
		//获取用户ID  Map类型
		String[] jf = { "user_id", "caption", "real_name", "user_education" };
		List<Map<String, Object>> ls_sum = AccessDataBaseUtil.query4ListMap(jf, querySql, null);
		
		if(verCode.equals(session_code)) {
			if(ls_sum.size() > 0) {
				// 取得用户ID
				Map<String, Object> user_map = ls_sum.get(0);
				// 给UserBean 赋值（用户ID,名称，登陆样式，布局）
				userBean.setUserId(user_map.get("user_id").toString());
				userBean.setUserrelName(user_map.get("caption").toString());
				userBean.setUserCss(user_map.get("real_name").toString());
				userBean.setUserLay(user_map.get("user_education").toString());
				userLay = user_map.get("user_education").toString();
				// 判断使用的数据库类别
				Session session = ConstantInfoHelper.hnbd.getSessionFactory().openSession();
				String dialect = ((SessionImpl) session).getFactory().getDialect().getClass().getName();
				String dbType = "";
				if(dialect.toLowerCase().indexOf("mysql") > 0) {
					dbType = "mysql";
				} else if(dialect.toLowerCase().indexOf("oracle") > 0) {
					dbType = "oracle";
				} else {
					dbType = "\"\"";
				}
				userBean.setDbType(dbType);// 给UserBean 赋值（数据库类型）
				userBean.setCurOrgId(nowOrg);// 给UserBean 赋值（当前选择机构ID）
				// 获取当前机构名称
				sql = "select caption from t_department where department_id = ?";
				List<Object> org_name = AccessDataBaseUtil.query4List(sql, new Object[] { nowOrg });
				if(null != org_name && org_name.size() > 0) {
					userBean.setCurOrgName(org_name.get(0).toString());
				} else {
					userBean.setCurOrgName("");
				}

				/*
				 * 获取用户机构的map add by changchun
				 */
				List<Map<String, String>> listAllOrgs = new ArrayList<Map<String, String>>();//所有机构的list
				List<Map<String, String>> listUserOrgs = new ArrayList<Map<String, String>>();//用户所有机构的list
				Map<String, Integer> maps = new HashMap<String, Integer>();//存储机构ID与子节点个数
				
				this.listAllOrg(listAllOrgs, null, maps, "0", "_");//获取所有机构
				sql = "select department_id from t_user_department where user_id = ?";
				List<Object> list = AccessDataBaseUtil.query4List(sql, new Object[]{ userBean.getUserId() });
				
				for(Object obj: list){
					String id = obj.toString();
					for(Map<String, String> map: listAllOrgs){
						if(id.equals(map.get("department_id"))){
							String child2 = maps.get(id) == null ? "0" : maps.get(id).toString();
							map.put("child2", child2);
							listUserOrgs.add(map);
						}
					}
				}

				Collections.sort(listUserOrgs, new Comparator<Map<String, String>>(){

					@Override
					public int compare(Map<String, String> o1, Map<String, String> o2) {
						return o1.get("ids").compareTo(o2.get("ids"));
					}
				});
				userBean.setOrgMap(listUserOrgs);//用户机构
				this.changeCurSubOrgId(userBean);//获取当前及以下机构的id串、拼装下拉列表的option
				/*
				 * 获取用户机构的map end by changchun
				 */
				
				// 获取用户环境变量
				Map<String, String> global_Map = new HashMap<String, String>();
				String sys_sql_user = "select sc_key,sc_value from t_system_config where sc_uid in ('0','" + user_map.get("user_id") + "') and sc_marked='1'";
				List<Map<String, Object>> user_gloabl = AccessDataBaseUtil.query4ListMap(sys_global, sys_sql_user, null);
				if(user_gloabl.size() > 0) {
					for(int i = 0; i < user_gloabl.size(); i++) {
						Map<String, Object> usergol_map = user_gloabl.get(i);
						global_Map.put(usergol_map.get("sc_key").toString(), usergol_map.get("sc_value").toString());
					}
				}
				userBean.setGlobalMap(global_Map);//获取用户的环境变量与系统环境变量

				/*
				 * 获取用户的所有快捷菜单信息 add by changchun
				 */
				Object[] params = { userBean.getUserId() };
				// 菜单
				List<Object> list2 = new ArrayList<Object>();
				List<Object> list1 = AccessDataBaseUtil.query4List(sql11, params);
				list2.addAll(list1);
				// 角色
				list1 = AccessDataBaseUtil.query4List(sql12, params);
				list2.addAll(list1);
				// 组
				list1 = AccessDataBaseUtil.query4List(sql13, params);
				list2.addAll(list1);

				String ids = "";
				if(list2.size() > 0) {
					for(Object obj: list2) {
						ids += "'" + obj + "',";
					}
				}
				ids += "''";

				String sql4 = "select permission_id, caption, action, quickIcon,types from t_permission where permission_id in ( "
						+ ids + ") and isQuick='Y' order by showorder";
				String[] jsonField = { "id", "name", "url", "icon", "types" };
				List<Map<String, Object>> listMap = AccessDataBaseUtil.query4ListMap(jsonField, sql4, null);
				if(null != listMap && listMap.size() > 0) {
					userBean.setQuickIconList(listMap);
				}
				/*
				 * 获取用户的所有快捷菜单信息 end by changchun
				 */

				/*
				 * 获取字典信息 add by changchun 2012-08-23
				 */
				Map<String, List<Map<String, String>>> dicMap = userBean.getDicMap();
				sql = "select tmgd_type,tmgd_description,tmgd_id,tmgd_name from tm_general_dictionary where tmgd_is_valid = '1' order by tmgd_order_num";
				String[] jsonField1 = { "tmgd_type", "tmgd_description", "tmgd_id", "tmgd_name" };
				List<Map<String, String>> list5 = AccessDataBaseUtil.query(jsonField1, sql, null);
				for(Map<String, String> map: list5) {
					List<Map<String, String>> list6 = dicMap.get(map.get("tmgd_type"));//获取userBean中的字典类型
					if(null == list6) {
						list6 = new ArrayList<Map<String, String>>();
						dicMap.put(map.get("tmgd_type"), list6);
					}
					list6.add(map);
				}
				/*
				 * 获取字典信息 end by changchun
				 */

				this.getRequest().getSession().setAttribute("userBean", userBean);// 添加成功信息
				msg = "\"登录成功\"";
				message = "sucess";
			} else {
				((HttpServletRequest) this.getRequest()).getSession().invalidate();// 添加失败信息
				msg = "\"登录失败\"";
				message = "error";
			}
		} else {
			msg = "\"验证码错误\"";
			message = "warn";
		}
		JSONObject request_jso = new JSONObject();
		request_jso.put("message", msg);
		request_jso.put("userlay", userLay);
		return request_jso;
	}

	/** 
	 * 描述：listOrg 登录时输入用户名，自动检索出其所拥有的机构
	 * @param jsonArray
	 * @return
	 * @throws Exception
	 * @CreateOn Sep 17, 2012  10:26:47 AM
	 * @author chun_chang
	 */
	public Object listOrg(Object jsonArray) throws Exception {
		JSONArray array = JSONArray.fromObject(jsonArray);
		JSONObject jsonObject = JSONObject.fromObject(array.getString(0));
		String userName = jsonObject.getString("userName");
		String userId = "";

		if(StringUtils.isBlank(userName)) {
			return null;
		} else {
			sql = "select user_id from t_user where action= ? ";
			List<Object> l = AccessDataBaseUtil.query4List(sql, new Object[] { userName } );
			if(l.size() <= 0){
				return null;
			}
			userId = l.get(0).toString();
			
			//取出显示机构级别
			Set<String> set = new HashSet<String>();
			sql = "select user_position_id from t_user_info where user_id = ?";
			List<Object> l1 = AccessDataBaseUtil.query4List(sql, new Object[] { userId } );
			String level = l1.get(0).toString();
			try {
				int lev = Integer.valueOf(level);
				switch(lev){
					case 1: set.add("0"); break;
					case 2: set.add("1"); break;
					case 3: set.add("0"); set.add("1"); break;
					case 4: set.add("2"); break;
					case 5: set.add("0"); set.add("2"); break;
					case 6: set.add("1"); set.add("2"); break;
					case 7: set.add("0"); set.add("1"); set.add("2"); break;
					case 8: set.add("3"); break;
					case 9: set.add("0"); set.add("3"); break;
					case 10: set.add("1"); set.add("3"); break;
					case 11: set.add("0"); set.add("1"); set.add("3"); break;
					case 12: set.add("2"); set.add("3"); break;
					case 13: set.add("0"); set.add("2"); set.add("3"); break;
					case 14: set.add("1"); set.add("2"); set.add("3"); break;
					case 15: set.add("0"); set.add("1"); set.add("2"); set.add("3"); break;
				}
			} catch (Exception e) {
			}
			
			List<Map<String, String>> listAllOrgs = new ArrayList<Map<String, String>>();
			List<Map<String, String>> listUserOrgs = new ArrayList<Map<String, String>>();
			Map<String, Integer> maps = new HashMap<String, Integer>();//存储机构ID与子节点个数
			this.listAllOrg(listAllOrgs, null, maps, "0", "_");
			sql = "select department_id from t_user_department where user_id = ?";
			List<Object> list = AccessDataBaseUtil.query4List(sql, new Object[]{ userId });
			
			for(Object obj: list){
				String id = obj.toString();
				for(Map<String, String> map: listAllOrgs){
					if(id.equals(map.get("department_id"))){
						if(set.size() > 0){
							String levels = map.get("levels");
							if(set.add(levels)){
								set.remove(levels);
								continue;
							}
						}
						String child2 = maps.get(id) == null ? "0" : maps.get(id).toString();
						map.put("child2", child2);
						listUserOrgs.add(map);
					}
				}
			}
			
			Collections.sort(listUserOrgs, new Comparator<Map<String, String>>(){
				
				@Override
				public int compare(Map<String, String> o1, Map<String, String> o2) {
					return o1.get("ids").compareTo(o2.get("ids"));
				}
				
			});
			return listUserOrgs;
		}
		
	}

	/** 
	 * 描述：changeCurSubOrgId 更改当前及以下机构ID
	 * @CreateOn Aug 29, 2012  4:43:44 PM
	 * @author chun_chang
	 */
	private void changeCurSubOrgId(UserBean userBean) {
		boolean isManage = false;
		String userId = userBean.getUserId();
		//如果是这3人只显示二级机构下拉框
		if("3baf3bb603e04d0688053555b0234b46".equals(userId)//张连芝
				|| "3df87eb3973f4eba8fa851686ceba0f6".equals(userId)//徐丹
				|| "defd78b884d744dcb55f123638dfdd4d".equals(userId)){//王亮
			isManage = true;
		}
		
		String curSubOrgId = "";
		String curSubOrgOptions = "";
		for(Map<String, String> map: userBean.getOrgMap()) {
			String levels = map.get("levels");
			String ids = map.get("ids");
			if(ids.indexOf(userBean.getCurOrgId()) > -1) {
				curSubOrgId += "'" + map.get("department_id") + "',";
				if(isManage){
					if("0".endsWith(levels) || "1".equals(levels)){
						curSubOrgOptions += "<option value=\"" + map.get("department_id") + "\">" + map.get("caption") + "</option>";
					}
				} else {
					curSubOrgOptions += "<option value=\"" + map.get("department_id") + "\">" + map.get("caption") + "</option>";
				}
			}
		}
		if(!"".equals(curSubOrgId)) {
			curSubOrgId = curSubOrgId.substring(0, curSubOrgId.length() - 1);
		}
		userBean.setCurSubOrgId(curSubOrgId);
		userBean.setCurSubOrgOptions(curSubOrgOptions);
	}
	
	/** 
	 * 描述：listAllOrg 查询所有的机构
	 * @param listAllOrgs
	 * @param pid
	 * @CreateOn Sep 17, 2012  9:51:49 AM
	 * @author chun_chang
	 * @throws Exception 
	 */
	private void listAllOrg(List<Map<String, String>> listAllOrgs,Map<String, String> mapp,Map<String, Integer> maps, String pid, String ids) throws Exception{
		sql = "select ";
		Session session = ConstantInfoHelper.hnbd.getSessionFactory().openSession();
		String dialect = ((SessionImpl) session).getFactory().getDialect().getClass().getName();
		if(dialect.toLowerCase().indexOf("mysql") > 0) {
			sql += "concat('" + ids + "_',d.department_id),";
		} else if(dialect.toLowerCase().indexOf("oracle") > 0) {
			sql += "'" + ids + "_' || d.department_id,";
		}
		sql += " d.department_id,d.caption,d.levels from t_department d where d.dparent_id = ?";
		String[] field = {
				"ids", "department_id", "caption", "levels"
		};
		List<Map<String, String>> list = AccessDataBaseUtil.query(field, sql, new Object[] { pid });
		if(null != list && list.size() > 0){
			listAllOrgs.addAll(list);
			if(!"0".equals(pid)){
				mapp.put("child", list.size()+"");
				String ids1 = mapp.get("ids").replaceAll("__", "");
				String[] ids11 = ids1.split("_");
				switch(ids11.length){
					case 1:
						maps.put(ids11[0], list.size() + (maps.get(ids11[0]) == null ?0:maps.get(ids11[0])));
						break;
					case 2:
						maps.put(ids11[1], list.size() + (maps.get(ids11[1]) == null ?0:maps.get(ids11[1])));
						maps.put(ids11[0], list.size() + (maps.get(ids11[0]) == null ?0:maps.get(ids11[0])));
						break;
					case 3:
						maps.put(ids11[2], list.size() + (maps.get(ids11[2]) == null ?0:maps.get(ids11[2])));
						maps.put(ids11[1], list.size() + (maps.get(ids11[1]) == null ?0:maps.get(ids11[1])));
						maps.put(ids11[0], list.size() + (maps.get(ids11[0]) == null ?0:maps.get(ids11[0])));
						break;
					default: break;
				}
			}
			
			for(Map<String, String> map: list) {
				String orgId = map.get("department_id");
				String name = map.get("caption");
				String ids1 = map.get("ids");
				int levels = Integer.valueOf(map.get("levels"));
				switch(levels){
				case 0: break;
				case 1: name = "-" + name; break;
				case 2: name = "--" + name; break;
				case 3: name = "---" + name; break;
				case 4: name = "----" + name; break;
				case 5: name = "-----" + name; break;
				case 6: name = "------" + name; break;
				case 7: name = "-------" + name; break;
				case 8: name = "--------" + name; break;
				case 9: name = "---------" + name; break;
				default: break;
				}
				map.put("caption", name);
				this.listAllOrg(listAllOrgs, map, maps,orgId, ids1);
			}
		} else {
			mapp.put("child", "0");
		}
	}
	
	/** 
	 * 描述：updateOrg 修改用户的当前机构
	 * @param jsonArray
	 * @return
	 * @throws Exception
	 * @CreateOn Aug 29, 2012  4:48:21 PM
	 * @author chun_chang
	 */
	public Object updateOrg(Object jsonArray) throws Exception {
		JSONArray array = JSONArray.fromObject(jsonArray);
		JSONObject jsonObject = JSONObject.fromObject(array.getString(0));
		String userOrgs = jsonObject.getString("userOrg");
		String[] userOrg = userOrgs.split("_");
		
		UserBean us = (UserBean) this.getRequest().getSession().getAttribute("userBean");// 获得userBean信息
		us.setCurOrgId(userOrg[0]);
		us.setCurOrgName(userOrg[1].replaceAll("-", ""));
		this.getRequest().getSession().setAttribute("userBean", us);// 重新赋值
		
		this.changeCurSubOrgId(us);
		return null;
	}
	
	/** 
	 * 描述：downloadLog 
	 * @param jsonArray
	 * @return
	 * @throws Exception
	 * @CreateOn Aug 13, 2012  1:41:51 PM
	 * @author chun_chang
	 */
	public Object downloadLog(Object jsonArray) throws Exception {
		String dir = ConstantInfoHelper.APPLICATION_PATH + "/logs/";
		ZipUtil.makeDirectoryToZip(dir);
		return "{\"url\":\"logs.zip\"}";
	}

	/** 
	 * 描述：logout 退出
	 * @param jsonArray
	 * @return
	 * @CreateOn Sep 17, 2012  9:37:20 AM
	 * @author chun_chang
	 */
	public Object logout(Object jsonArray) {
		this.getRequest().getSession().setAttribute("userBean", null);
		this.getRequest().getSession().invalidate();
		return null;
	}

	@Override
	public Object insert(Object jsonArray) throws Exception {
		return null;
	}

	@Override
	public Object update(Object jsonArray) throws Exception {
		return null;
	}

	@Override
	public Object delete(Object jsonArray) throws Exception {
		return null;
	}

	@Override
	public Object updateBatch(Object jsonArray) throws Exception {
		return null;
	}

	@Override
	public Object recordCount(Object jsonArray) throws Exception {
		return null;
	}

	@Override
	public Object setRequest(HttpServletRequest request) throws Exception {
		this.request = request;
		return this.request;
	}

	private String sql11 = "select a.permission_id from t_permission a,t_user_permission b where a.permission_id = b.permission_id and b.user_id = ?";
	private String sql12 = "select c.permission_id from t_permission c,t_role_permission d,t_role e,t_user_role f where c.permission_id = d.permission_id and d.role_id = e.role_id and e.role_id = f.role_id and f.user_id = ?";
	private String sql13 = "select h.permission_id from t_permission h,t_role_permission i,t_role j,t_group_role k,t_group l,t_user_group m where h.permission_id = i.permission_id and i.role_id = j.role_id and j.role_id = k.role_id and k.group_id = l.group_id and l.group_id = m.group_id and m.user_id = ?";

}
